/**
 * @file HTTP 请求统一处理
 * @author dafo<huanghoujin@baijia.com>
 */
import axios from 'axios';
import {message} from 'antd';
import {debounce} from 'lodash';
import {BaseUrl} from '~/utils/common/envType';
import constant from './constant';

const baseURL = BaseUrl;
// 后端限流的状态码
export const CODE_7001 = 7001;

axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

const instance = axios.create({
    baseURL,
    withCredentials: true,
});

const debounce7001 = debounce(data => {
    message.info(data.msg);
}, 1000);

const success = ({data, config, headers}) => {
    const {responseType} = config || {};
    const contentType = headers?.['content-type'];
    // 文件下载失败逻辑判断：请求体的 responseType 是 blob，返回值的 contentType 不是 application/x-download
    if (responseType === 'blob' && !contentType?.includes('x-download')) {
        debounce7001({msg: '您的数据正在搬运中，请稍后重试'});
        return Promise.reject();
    }

    if (data.code === CODE_7001) {
        // message.info(data.msg);
        debounce7001(data);
        return Promise.reject(CODE_7001);
    }

    if (data.code && data.code === constant.HttpCode.RELOGIN) {
        const envType = process.env.ENV_TYPE || 'local';
        window.location.href = envType === 'local'
            ? `${BaseUrl}/api/report/main`
            : '/api/report/main';
    }
    if ((data.code && data.code > 0) || (data.status && data.status !== constant.HttpCode.OK)) {
        if (data.msg) {
            message.error(data.msg);
            return null;
        }
        message.error('未知失败，请重试！');
        return null;
    }
    // 数据返回
    return data;
};

const failData = {
    code: constant.HttpCode.TIMEOUT,
    msg: 'timeout',
};

const fail = res => {
    if (res.code === CODE_7001) {
        message.info(res.msg);
        return Promise.reject(CODE_7001);
    }

    const {config, response} = res;
    if (response && response.data && response.data.code > 0) {
        if (response.data.msg) {
            message.error(response.data.msg);
            return null;
        }
        message.error('未知失败，请重试！');
        return null;
    }

    if (!config || !config.retry) {
        return Promise.reject(failData);
    }

    config.retryCount = (config.retryCount | 0) + 1;
    if (config.retryCount > config.retry) {
        return Promise.resolve(failData);
    }

    return new Promise(resolve => setTimeout(resolve, config.retryDelay)).then(() => instance.request(config));
};

instance.interceptors.request.use(
    config => {
        config.headers['Content-Type'] = 'application/json';
        return config;
    }
);

instance.interceptors.response.use(success, fail);

instance.axios = axios;

export default instance;
